import { randomUUID } from "node:crypto";

// 简单的HTTP MCP客户端测试
class SimpleMcpClient {
  private baseUrl: string;
  private sessionId: string | null = null;

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }

  private async makeRequest(method: string, body?: any) {
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
    };

    if (this.sessionId) {
      headers["mcp-session-id"] = this.sessionId;
    }

    const response = await fetch(this.baseUrl, {
      method,
      headers,
      body: body ? JSON.stringify(body) : undefined,
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const result = await response.json();
    
    // 如果是初始化响应，提取会话ID
    if (result.result && result.result.sessionId) {
      this.sessionId = result.result.sessionId;
      console.log(`✅ Session established: ${this.sessionId}`);
    }

    return result;
  }

  async initialize() {
    console.log("🔄 Initializing MCP connection...");
    const response = await this.makeRequest("POST", {
      jsonrpc: "2.0",
      id: randomUUID(),
      method: "initialize",
      params: {
        protocolVersion: "2024-11-05",
        capabilities: {
          tools: {},
          resources: {},
        },
        clientInfo: {
          name: "test-client",
          version: "1.0.0",
        },
      },
    });
    return response;
  }

  async listTools() {
    console.log("📋 Listing available tools...");
    const response = await this.makeRequest("POST", {
      jsonrpc: "2.0",
      id: randomUUID(),
      method: "tools/list",
      params: {},
    });
    return response;
  }

  async listResources() {
    console.log("📚 Listing available resources...");
    const response = await this.makeRequest("POST", {
      jsonrpc: "2.0",
      id: randomUUID(),
      method: "resources/list",
      params: {},
    });
    return response;
  }

  async callTool(name: string, arguments_: any) {
    console.log(`🔧 Calling tool: ${name}`);
    const response = await this.makeRequest("POST", {
      jsonrpc: "2.0",
      id: randomUUID(),
      method: "tools/call",
      params: {
        name,
        arguments: arguments_,
      },
    });
    return response;
  }

  async readResource(uri: string) {
    console.log(`📖 Reading resource: ${uri}`);
    const response = await this.makeRequest("POST", {
      jsonrpc: "2.0",
      id: randomUUID(),
      method: "resources/read",
      params: {
        uri,
      },
    });
    return response;
  }
}

// 测试函数
async function runTests() {
  const client = new SimpleMcpClient("http://localhost:3000/mcp");

  try {
    // 1. 初始化连接
    const initResponse = await client.initialize();
    console.log("✅ Initialize response:", JSON.stringify(initResponse, null, 2));

    // 2. 列出工具
    const toolsResponse = await client.listTools();
    console.log("✅ Tools response:", JSON.stringify(toolsResponse, null, 2));

    // 3. 列出资源
    const resourcesResponse = await client.listResources();
    console.log("✅ Resources response:", JSON.stringify(resourcesResponse, null, 2));

    // 4. 测试计算器工具
    const calcResponse = await client.callTool("calculator", {
      operation: "add",
      a: 10,
      b: 5,
    });
    console.log("✅ Calculator response:", JSON.stringify(calcResponse, null, 2));

    // 5. 测试回声工具
    const echoResponse = await client.callTool("echo", {
      text: "Hello, MCP World!",
    });
    console.log("✅ Echo response:", JSON.stringify(echoResponse, null, 2));

    // 6. 读取系统信息资源
    const sysInfoResponse = await client.readResource("system://info");
    console.log("✅ System info response:", JSON.stringify(sysInfoResponse, null, 2));

    // 7. 读取时间资源
    const timeResponse = await client.readResource("time://current");
    console.log("✅ Time response:", JSON.stringify(timeResponse, null, 2));

    console.log("\n🎉 All tests completed successfully!");
  } catch (error) {
    console.error("❌ Test failed:", error);
    process.exit(1);
  }
}

// 检查服务器是否运行
async function checkServer() {
  try {
    const response = await fetch("http://localhost:3000/health");
    if (response.ok) {
      const health = await response.json();
      console.log("🏥 Server health:", health);
      return true;
    }
  } catch (error) {
    console.error("❌ Server is not running. Please start the server first with: npm run dev");
    return false;
  }
  return false;
}

// 主函数
async function main() {
  console.log("🧪 Starting MCP Client Tests...");
  
  const serverRunning = await checkServer();
  if (!serverRunning) {
    process.exit(1);
  }

  await runTests();
}

// 运行测试
if (import.meta.url === `file://${process.argv[1]}`) {
  main().catch(console.error);
}

export { SimpleMcpClient };